<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Laravel," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="本文内容来自于JellyBool的视频，地址: Laravel 实战开发知乎：前后端分离 API token 认证 

Laravel 前端API Token认证Laravel 的 API 认证提供了两种方式，一是使用 passport package，二是使用 token来进行认证，今天使用的是token方式来认证。
查看Laravel源码TokenGuard.php可以看到   12$thi">
<meta property="og:type" content="article">
<meta property="og:title" content="Laravel 前端API Token认证">
<meta property="og:url" content="http://yoursite.com/2017/04/18/Laravel-前端API-Token认证/index.html">
<meta property="og:site_name" content="EasyBlog">
<meta property="og:description" content="本文内容来自于JellyBool的视频，地址: Laravel 实战开发知乎：前后端分离 API token 认证 

Laravel 前端API Token认证Laravel 的 API 认证提供了两种方式，一是使用 passport package，二是使用 token来进行认证，今天使用的是token方式来认证。
查看Laravel源码TokenGuard.php可以看到   12$thi">
<meta property="og:updated_time" content="2017-04-18T07:52:00.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Laravel 前端API Token认证">
<meta name="twitter:description" content="本文内容来自于JellyBool的视频，地址: Laravel 实战开发知乎：前后端分离 API token 认证 

Laravel 前端API Token认证Laravel 的 API 认证提供了两种方式，一是使用 passport package，二是使用 token来进行认证，今天使用的是token方式来认证。
查看Laravel源码TokenGuard.php可以看到   12$thi">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/04/18/Laravel-前端API-Token认证/"/>





  <title> Laravel 前端API Token认证 | EasyBlog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?07a6d49ae67fe991e0ce3c2f3955e0f9";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">EasyBlog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/04/18/Laravel-前端API-Token认证/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gasbylei">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://gasbylei.github.io/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="EasyBlog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">
            
            
              
                Laravel 前端API Token认证
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-18T15:34:45+08:00">
                2017-04-18
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/04/18/Laravel-前端API-Token认证/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2017/04/18/Laravel-前端API-Token认证/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本文内容来自于JellyBool的视频，地址: <a href="https://www.laravist.com/series/build-a-zhihu-website-with-laravel/episodes/21" target="_blank" rel="external">Laravel 实战开发知乎：前后端分离 API token 认证 </a></p>
</blockquote>
<h1 id="Laravel-前端API-Token认证"><a href="#Laravel-前端API-Token认证" class="headerlink" title="Laravel 前端API Token认证"></a>Laravel 前端API Token认证</h1><p>Laravel 的 API 认证提供了两种方式，一是使用 <code>passport</code> package，二是使用 <code>token</code>来进行认证，今天使用的是<code>token</code>方式来认证。</p>
<h3 id="查看Laravel源码TokenGuard-php可以看到"><a href="#查看Laravel源码TokenGuard-php可以看到" class="headerlink" title="查看Laravel源码TokenGuard.php可以看到"></a>查看Laravel源码<code>TokenGuard.php</code>可以看到</h3>   <figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">$this</span>-&gt;inputKey = <span class="string">'api_token'</span>;</div><div class="line"><span class="keyword">$this</span>-&gt;storageKey = <span class="string">'api_token'</span>;</div></pre></td></tr></table></figure>
<p>   laravel规定<code>inputKey</code>为<code>api_token</code>,因此我们创建为用户创建的字段名也得为<code>api_token</code>.</p>
<h3 id="为用户表添加字段api-token"><a href="#为用户表添加字段api-token" class="headerlink" title="为用户表添加字段api_token"></a>为用户表添加字段<code>api_token</code></h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&gt; php artisan make:migration add_api_token_to_users --table=users</div></pre></td></tr></table></figure>
<p>在<code>add_api_token_to_users.php</code>中修改如下：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"> <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">up</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    Schema::table(<span class="string">'users'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(Blueprint $table)</span> </span>&#123;</div><div class="line">        $table-&gt;string(<span class="string">'api_token'</span>,<span class="number">64</span>)-&gt;unique();</div><div class="line">    &#125;);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">down</span><span class="params">()</span></span></div><div class="line">&#123;</div><div class="line">    Schema::table(<span class="string">'users'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(Blueprint $table)</span> </span>&#123;</div><div class="line">        $table-&gt;dropColumn([<span class="string">'api_token'</span>]);</div><div class="line">    &#125;);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">&gt; php artisan migrate</div></pre></td></tr></table></figure>
<p>进行上面操作后，在user表中可以看到已经多了一个<code>api_token</code>字段。</p>
<a id="more"></a>
<h3 id="这时我们需要在注册用户时为其随机生成一个api-token。"><a href="#这时我们需要在注册用户时为其随机生成一个api-token。" class="headerlink" title="这时我们需要在注册用户时为其随机生成一个api_token。"></a>这时我们需要在注册用户时为其随机生成一个<code>api_token</code>。</h3><p>进入<code>RegisterController.php</code>在<code>create</code>方法中加入如下：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="string">'api_token'</span> =&gt;str_random(<span class="number">60</span>)</div></pre></td></tr></table></figure>
<p>在<code>User.php</code>的<code>$fillable</code>字段中添加<code>api_token</code>表示其可以创建。</p>
<h3 id="使用Vue组件，因此需要给vue发送请求时添加认证。"><a href="#使用Vue组件，因此需要给vue发送请求时添加认证。" class="headerlink" title="使用Vue组件，因此需要给vue发送请求时添加认证。"></a>使用<code>Vue</code>组件，因此需要给<code>vue</code>发送请求时添加认证。</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">Vue.http.interceptors.push((request, next) =&gt; &#123;</div><div class="line">request.headers.set(&apos;X-CSRF-TOKEN&apos;, Laravel.csrfToken);</div><div class="line">request.headers.set(&apos;Authorization&apos;, Laravel.apiToken);//这是添加的</div><div class="line"></div><div class="line">next();</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>下面我们需要去<code>layout/app.blade.php</code>中设置 <code>Laravel.apiToken</code>，代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"> &lt;script&gt;</div><div class="line">    <span class="built_in">window</span>.Laravel = <span class="xml"><span class="php"><span class="meta">&lt;?php</span> <span class="keyword">echo</span> json_encode([</span></span></div><div class="line">        <span class="string">'csrfToken'</span> =&gt; csrf_token(),</div><div class="line">    ]); <span class="meta">?&gt;</span>;</div><div class="line">    Laravel.apiToken = "&#123;&#123; Auth::check() ? 'Bearer '.Auth::user()-&gt;api_token :  'Bearer ' &#125;&#125;";</div><div class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></div></pre></td></tr></table></figure>
<p><code>Laravel.apiToken</code>先判断用户是否登录，若登录则<code>apiToken</code>为<code>Bearer +api_token</code>，反之为<code>Bearer</code>。</p>
<p>此时，API Token认证已经完成，可以去进行测试了！</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Laravel/" rel="tag"># Laravel</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/04/17/Laravel-ide-helper-高效的IDE-智能提示插件/" rel="next" title="Laravel-ide-helper 高效的IDE 智能提示插件">
                <i class="fa fa-chevron-left"></i> Laravel-ide-helper 高效的IDE 智能提示插件
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/04/20/Laravel-Notifications实现站内信通知/" rel="prev" title="Laravel Notifications实现站内信通知">
                Laravel Notifications实现站内信通知 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://gasbylei.github.io/uploads/avatar.png"
               alt="Gasbylei" />
          <p class="site-author-name" itemprop="name">Gasbylei</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">17</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/Gasbylei" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Laravel-前端API-Token认证"><span class="nav-number">1.</span> <span class="nav-text">Laravel 前端API Token认证</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#查看Laravel源码TokenGuard-php可以看到"><span class="nav-number">1.0.1.</span> <span class="nav-text">查看Laravel源码TokenGuard.php可以看到</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#为用户表添加字段api-token"><span class="nav-number">1.0.2.</span> <span class="nav-text">为用户表添加字段api_token</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#这时我们需要在注册用户时为其随机生成一个api-token。"><span class="nav-number">1.0.3.</span> <span class="nav-text">这时我们需要在注册用户时为其随机生成一个api_token。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用Vue组件，因此需要给vue发送请求时添加认证。"><span class="nav-number">1.0.4.</span> <span class="nav-text">使用Vue组件，因此需要给vue发送请求时添加认证。</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gasbylei</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'gatsbylei';
      var disqus_identifier = '2017/04/18/Laravel-前端API-Token认证/';

      var disqus_title = "Laravel 前端API Token认证";


      function run_disqus_script(disqus_script) {
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');

      
        var disqus_config = function () {
            this.page.url = disqus_url;
            this.page.identifier = disqus_identifier;
            this.page.title = disqus_title;
        };
        run_disqus_script('embed.js');
      

    </script>
  










  
  

  

  

  

  


  

</body>
</html>
